import { Plus, X } from 'lucide-react';
import { useEffect, useState } from 'react';

import { addProject, removeProject } from '@/redux/projects/projectsSLice';
import { useAppDispatch } from '@/hook/useRedux';

import { Button } from '@/components/ui/button';
import { AlertAnswer } from '@/components/Customs/AlertAnswer';
import { DialogInput } from '@/components/Customs/DialogInput';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import useFetchProjects from '@/hook/useFetchProjects';


export const BoardHeader = () => {
  const [, setValue] = useState<string>('');
  const [deleteIdProject, setDeleteIdProject] = useState<{ id: string, name: string } | null>();
  const [open, setOpen] = useState(false);

  const { handleProjectSelect, projects, status, selectedProjectId } = useFetchProjects()
  const dispatch = useAppDispatch();


  useEffect(() => {
    if (status === 'success') {
      setValue(selectedProjectId)
    }
  }, [status]);


  const onSubmit = (value: string) => {
    dispatch(addProject({ value }))
    defaultSetting();
  };

  const defaultSetting = () => {
    if (!localStorage.getItem('selectedProjectId')) {
      projects.length && setValue(projects[0].id);
    } else {
      const lcl = localStorage.getItem('selectedProjectId') || ''
      setValue(lcl)
    }
    setOpen(false);
  };

  const handleChangeBoard = (id: string) => {
    setValue(id);
    handleProjectSelect(id);
  };

  const handleDeletProject = () => {
    if (deleteIdProject) {
      dispatch(removeProject(deleteIdProject.id));
      resetConfig();
    }
  };

  const resetConfig = () => {
    setDeleteIdProject(null)
  }

  return (
    <div className='flex w-full items-center gap-4 p-2'>
      <div>
        <h2 className='text-xl font-medium'>Проекты: </h2>
      </div>
      <Tabs className='w-auto overflow-x-auto grow scrollBar ' onValueChange={handleChangeBoard} value={selectedProjectId}>
        <TabsList className='w-full justify-start gap-1'>
          {projects?.length &&
            projects.map((project) => (
              <TabsTrigger
                key={project.id}
                value={project.id}
                className='group/project  relative bg-slate-200 hover:bg-white px-10'
              >
                {project.name}
                <span
                  className=' invisible absolute right-1 top-[calc(50%-8px)] z-10 flex items-center justify-center rounded-full  hover:bg-slate-800 group-hover/project:visible hover:text-white'
                  onClick={() => setDeleteIdProject({ id: project.id, name: project.name })}
                >
                  <X size={16} />
                </span>
              </TabsTrigger>
            ))}
          <Button
            className={` rounded-sm bg-slate-200 py-[6px] hover:bg-white`}
            onClick={() => setOpen(true)}
            variant={'secondary'}
          >
            <Plus strokeWidth={2} size={16} className='mr-1' /> Создать Проект
          </Button>
        </TabsList>
      </Tabs>
      <DialogInput
        text='Введите название проекта'
        onCancel={defaultSetting}
        onSubmit={onSubmit}
        open={open}
      />
      <AlertAnswer
        open={!!deleteIdProject}
        accept={handleDeletProject}
        cancel={resetConfig}
        text={`Вы действительно хотите удалить проект ${deleteIdProject?.name}?`}
      />
    </div>
  );
};
